package com.wdg.interceptor;

import com.wdg.dao.LogDao;
import com.wdg.dao.UserDao;
import com.wdg.dao.impl.LogDaoImpl;
import com.wdg.dao.impl.UserDaoImpl;
import com.wdg.pojo.Login_log;
import com.wdg.pojo.Reg_user;
import com.wdg.util.DateUtil;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.net.InetAddress;

public class RecordLogInterceptor implements HandlerInterceptor {
	LogDao ldao=new LogDaoImpl();
	UserDao dao=new UserDaoImpl();
	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object arg2, Exception arg3)
			throws Exception {
		HttpSession session = request.getSession();
		String logname = (String) session.getAttribute("username");
		Reg_user u = dao.getUser(logname);
		String userAction=request.getServletPath();
		if(userAction.indexOf("login.action")>=0){
			userAction="登录后台";
		}else if(userAction.indexOf("delUserById.action")>=0){
			userAction="删除用户";
		}else if(userAction.indexOf("modifyUser.action")>=0){
			userAction="修改账户";
		}

		if (logname != null) {
			String logtime = DateUtil.getDate();
			String logip = InetAddress.getLocalHost().getHostAddress();
			
			Login_log l = new Login_log();
			l.setUser(logname);
			l.setUser_id(u.getId());
			l.setLog_time(logtime);
			l.setLog_ip(logip);

			l.setLog_action(userAction);

			ldao.addlog(l);
			System.out.println(logname + "被记录到日志中！动作行为："+userAction);
		}
	}
}
